package cn.iocoder.yudao.framework.redis.utils;

import cn.iocoder.yudao.framework.common.util.spring.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtils {

    private static RedisTemplate<Object, Object> template;

    private static RedissonClient client;


    public static RedisTemplate template() {
        if (template == null) {
            synchronized (RedisUtils.class) {
                if (template == null) {
                    template = SpringContextUtils.getBean("redisTemplate");
                    Objects.requireNonNull(template, "RedisClient must not be null");
                }
            }
        }
        return template;
    }

    public static RedissonClient client() {
        if (client == null) {
            synchronized (RedisUtils.class) {
                if (client == null) {
                    client = SpringContextUtils.getBean("redissonClient");
                    Objects.requireNonNull(client, "RedissonClient must not be null");
                }
            }
        }
        return client;
    }

    // 存储字符串到 Redis
    public static void setString(String key, String value) {
        RBucket<String> bucket = client().getBucket(key);
        bucket.set(value);
    }

    // 从 Redis 中获取字符串
    public static String getString(String key) {
        RBucket<String> bucket = client().getBucket(key);
        return bucket.get();
    }

    // 存储字符串到 Redis，并设置过期时间（秒）
    public static void setStringWithExpiration(String key, String value, long expirationInSeconds) {
        RBucket<String> bucket = client().getBucket(key);
        bucket.set(value, expirationInSeconds, TimeUnit.SECONDS);
    }

}
